// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const rightCollection = db.collection('right')
const userCollection = db.collection('user')

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const page = event.page || 1
  const pageSize = event.pageSize || 10
  const currentPage = (page - 1) * pageSize
  const state = event.state // 'hasRight' 'applyRight'
  let rightList = []
  let list1 = []
  let list2 = []
  if (state == 'hasRight'){
    await rightCollection.where({
      righter: wxContext.OPENID,
      status: 2
    }).skip(currentPage).limit(pageSize).orderBy('applyDate', 'desc').get().then(res => {
      list1 = res.data
    })
    for (let item of list1) {
      await userCollection.where({
        _openid: item.righted
      }).get().then(res => {
        item.rightUserInfo = res.data[0]
      })
    }
    await rightCollection.where({
      righted: wxContext.OPENID,
      status: 2
    }).skip(currentPage).limit(pageSize).orderBy('applyDate', 'desc').get().then(res => {
      list2 = res.data
    })
    for (let item of list2) {
      await userCollection.where({
        _openid: item.righter
      }).get().then(res => {
        item.rightUserInfo = res.data[0]
      })
    }
    let list = list1.concat(list2)
    rightList = list.sort((c1, c2) => {
      let val1 = c1.applyDate
      let val2 = c2.applyDate
      if(val1<val2){
        return -1
      }else if(val1>val2){
        return 1
      }else{
        return 0
      }
    })
  } else if (state == 'applyRight') {
    await rightCollection.where({
      righted: wxContext.OPENID,
      status: 1
    }).skip(currentPage).limit(pageSize).orderBy('applyDate', 'desc').get().then(res => {
      rightList = res.data
    })
    for (let item of rightList) {
      await userCollection.where({
        _openid: item.righter
      }).get().then(res => {
        item.rightUserInfo = res.data[0]
      })
    }
  }

 
  
  
  return rightList
}